package com.qhm123.spark.lucene;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldSelectorResult;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;

import com.qhm123.spark.model.Book;
import com.qhm123.spark.model.DbHelper;

public class Demo {

	static String indexPath = "/home/mingq/lucene_index/demo";

	public static void main(String[] args) throws IOException {

		Directory dir = FSDirectory.open(new File(indexPath));
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_33);
		IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_33,
				analyzer);
		// create
		iwc.setOpenMode(OpenMode.CREATE);

		IndexWriter writer = new IndexWriter(dir, iwc);
		indexDb(writer);

		writer.close();

		try {
			search();
		} catch (ParseException e) {
			e.printStackTrace();
		}

		// old();
	}

	private static void search() throws ParseException {
		try {
			IndexSearcher searcher = new IndexSearcher(
					FSDirectory.open(new File(indexPath)));
			Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_33);
			String field = "contents";
			QueryParser parser = new QueryParser(Version.LUCENE_33, field,
					analyzer);
			String q = "算法导论";
			Query query = parser.parse(q);
			System.out.println("searching for: " + query.toString(field));

			TopDocs results = searcher.search(query, 10);
			ScoreDoc[] hits = results.scoreDocs;

			int numTotalHits = results.totalHits;
			System.out.println(numTotalHits + " total matching documents");

			for (int i = 0; i < numTotalHits; i++) {
				System.out.println("doc=" + hits[i].doc + " score="
						+ hits[i].score);

				Document doc = searcher.doc(hits[i].doc);
				String id = doc.get("id");
				System.out.println("##Id: " + id);

				String title = doc.get("title");
				System.out.println("##Title: " + title);
			}

			searcher.close();

		} catch (CorruptIndexException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void indexDb(IndexWriter writer) {
		List<Book> books = DbHelper.getInstance().getBooks();

		for (Book book : books) {
			Document doc = new Document();
			// TODO: 添加Filed，建立索引
			doc.add(new Field("contents", book.summary, Field.Store.YES,
					Field.Index.ANALYZED));
			doc.add(new Field("id", book.id, Field.Store.YES, Field.Index.NO));
			doc.add(new Field("author", book.author, Field.Store.YES,
					Field.Index.ANALYZED));
			doc.add(new Field("title", book.title, Field.Store.YES,
					Field.Index.ANALYZED));
			try {
				writer.addDocument(doc);
			} catch (CorruptIndexException e) {
			} catch (IOException e) {
			}
		}
	}

	private static void old() throws CorruptIndexException,
			LockObtainFailedException, IOException {
		RAMDirectory directory = new RAMDirectory();
		IndexWriter writer = new IndexWriter(directory, new SimpleAnalyzer(),
				true, IndexWriter.MaxFieldLength.UNLIMITED);

		Document doc = new Document();
		doc.add(new Field("partnum", "Q36", Field.Store.YES,
				Field.Index.NOT_ANALYZED));
		doc.add(new Field("description", "Illidium Space Modulator",
				Field.Store.YES, Field.Index.ANALYZED));
		writer.addDocument(doc);
		writer.close();

		IndexSearcher searcher = new IndexSearcher(directory);
		Query query = new TermQuery(new Term("partnum", "Q36"));
		TopDocs rs = searcher.search(query, null, 10);
		System.out.println(rs.totalHits);

		Document firstHit = searcher.doc(rs.scoreDocs[0].doc);
		System.out.println(firstHit.getField("partnum").name());
	}
}
